package com.zk.babala.datasource;

import android.content.Intent;
import android.widget.Toast;

import com.zk.babala.BabalaApp;
import com.zk.babala.activity.CookiesWebViewActivity;
import com.zk.babala.entity.CategoryInfo;
import com.zk.babala.entity.LineInfo;
import com.zk.babala.entity.Movie;
import com.zk.babala.entity.PlayNumInfo;
import com.zk.babala.entity.VideoInfo;
import com.zk.babala.service.ISourceParse;
import com.zk.babala.util.Constant;
import com.zk.babala.util.LineUtil;
import com.zk.babala.util.RequestUtil;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.EscapeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * OmoFun动漫
 */
public class OmoFunSource implements ISourceParse {
    private String nextUrl;

    @Override
    public Map<String, String> getSourceMeta() {
        Map<String, String> map = new HashMap<>();
        map.put("source", this.getClass().getSimpleName());
        map.put("name", "OMOFUN");
        map.put("url", "https://cn.211dm.com/");
        return map;
    }

    public OmoFunSource() {

    }


    @Override
    public List<CategoryInfo> getCategory() {
        String line = LineUtil.getLineUtil().getLine();
        List<CategoryInfo> categoryInfoList = new ArrayList<>();
        categoryInfoList.add(new CategoryInfo("热播", line));
        categoryInfoList.add(new CategoryInfo("国漫", line + "type/2.html"));
        categoryInfoList.add(new CategoryInfo("动画", line + "type/5.html"));
        categoryInfoList.add(new CategoryInfo("日漫", line + "type/1.html"));
        CategoryInfo jc = new CategoryInfo("剧场", line + "type/24.html");
        jc.getChildList().add(new CategoryInfo("热血", line + "show/24---热血--------.html"));
        jc.getChildList().add(new CategoryInfo("武侠", line + "show/24---武侠--------.html"));
        jc.getChildList().add(new CategoryInfo("恐怖", line + "show/24---恐怖--------.html"));
        jc.getChildList().add(new CategoryInfo("剧情", line + "show/24---后宫--------.html"));

        categoryInfoList.add(jc);
        return categoryInfoList;
    }

    @Override
    public List<Movie> getMovies(String url) {
        List<Movie> list = new ArrayList<>();
        Document document = RequestUtil.get(url);
        if (document.getElementsByTag("title").get(0).text().contains("系统安全验证")) {
            Toast.makeText(BabalaApp.getContext(), "识别到有系统安全验证，点击认证后重新加载！", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(BabalaApp.getContext(), CookiesWebViewActivity.class);
            intent.putExtra("url", url);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            BabalaApp.getContext().startActivity(intent);

        }

        document.getElementsByClass("daFJ_dJJfFHa__aAICe").forEach(a -> {
            if (!a.attr("title").isEmpty()) {
                Movie m = new Movie();
                m.setTitle(a.attr("title"));
                m.setVideoUrl(LineUtil.getLineUtil().swapUrl(a.attr("href")));
                m.setCardImageUrl(LineUtil.getLineUtil().swapUrl(a.attr("data-original")));
                list.add(m);
            }

        });
        Elements pageElement = document.getElementsByClass("daFJ_aFJe__aEge");
        nextUrl = null;
        if (!pageElement.isEmpty()) {
            pageElement.get(0).getElementsByTag("a").forEach(page -> {
                if (page.text().equals("下一页")) {
                    nextUrl = page.attr("href");
                }
            });

        }
        return list;
    }

    @Override
    public VideoInfo getVideoDetail(String url) {
        VideoInfo videoInfo = new VideoInfo();
        Document document = RequestUtil.get(url);
        Element detail = document.getElementsByClass("daFJ_iJEdJHa__cFAFeA").get(0);
        Elements infoNodes = detail.getElementsByTag("p");
        infoNodes.forEach(infoNode -> {
            videoInfo.getDetailInfoList().add(infoNode.text());
        });

        List<LineInfo> lineInfoList = new ArrayList<>();
        Elements playNodes = document.getElementsByClass("channel-tab").get(0).getElementsByTag("a");

        for (int i = 0; i < playNodes.size(); i++) {
            Element node = playNodes.get(i);
            List<PlayNumInfo> playItemList = new ArrayList<>();
            String lineId = node.attr("href").replace("#", "");
            Elements playList = document.getElementById(lineId).getElementsByTag("a");
            for (int p = 0; p < playList.size(); p++) {
                Element item = playList.get(p);
                PlayNumInfo play = new PlayNumInfo();
                play.setId(p);
                play.setTitle(item.text());
                play.setPlayType(Constant.PLAY_TYPE_WEBVIEW);
                play.setPageUrl(item.attr("href"));
                playItemList.add(play);
            }

            LineInfo lineInfo = new LineInfo();
            lineInfo.setTitle(node.text());
            lineInfo.setPlayNumInfoList(playItemList);
            lineInfoList.add(lineInfo);
        }

        videoInfo.setLineInfoList(lineInfoList);
        return videoInfo;
    }

    @Override
    public String getPlayUrl(String url) {
        Document document = RequestUtil.get(url);
        //线路
        String line = document.getElementsByClass("play-channel-item active").get(0).text();
        JSONObject videoJson = JSONUtil.parseObj(document.getElementsByClass("daFJ_aJEaJD__eaJJJ").get(0).getElementsByTag("script").get(0).childNodes().get(0).toString().substring(16));
        String videoUrl = videoJson.getStr("url");
        if ("暴风".equals(line)) {
            videoUrl = EscapeUtil.unescape(videoUrl);
        }
        String next = videoJson.getStr("url_next");
        String pic = videoJson.getByPath("vod_data.vod_pic").toString();
        if (pic.startsWith("upload")) {
            pic = LineUtil.getLineUtil().getLine() + pic;
        }
        String name = videoJson.getByPath("vod_data.vod_name") + "";
        String dmid = document.getElementsByClass("mac_ulog_set hide").get(0).attr("data-id");
        String param = videoUrl + "&dmid=" + dmid + "&next" + next + "&pic=" + pic + "&name=" + name;


        if ("土豆".equals(line)) {
            return "https://art2.v2player.top:8989/player/?t=td&url=" + param;
        }

        if ("风车".equals(line)) {
            return "https://art2.v2player.top:8989/player/?t=bus&url=" + param;
        }

        return "https://art.v2player.top:8989/player/?url=" + param;
    }

    @Override
    public String getSearchUrl() {
        return LineUtil.getLineUtil().getLine() + "search/-------------.html?wd=";
    }


    @Override
    public List<Movie> search(String word) {
        String searchUrl = getSearchUrl() + word;
        nextUrl = null;
        return getMovies(searchUrl);
    }

    @Override
    public List<Movie> loadNext() {
        if (nextUrl == null) {
            return Collections.emptyList();
        } else {
            return getMovies(nextUrl);
        }
    }


}
